<template>
  <div
    :class="[
      'chat-bubble-container',
      isUser ? 'user-container' : 'bot-container',
    ]"
  >
    <!-- 用户消息布局 -->
    <div v-if="isUser" class="chat-bubble user-message">
      <div v-html="text"></div>
    </div>

    <!-- 机器人消息布局，包括头像和消息气泡 -->
    <div v-if="!isUser" class="avatar-and-message">
      <!-- 机器人头像 -->
      <img src="@/assets/touxiang.png" alt="Bot" class="bot-avatar" />

      <div class="chat-bubble bot-message">
        <div>
          <!--显示文字描述-->
          <!-- <div v-html="renderedText"></div> -->
          <v-md-preview v-model:text="renderedText"></v-md-preview>

          <!--显示echarts-->
          <div v-if="chart && !showTable" class="chart-container">
            <EChartsComponent
              :options="parsedChart"
              @data-selected="handleDataSelected"
            />
          </div>

          <!--显示数据表格-->
          <div v-if="(table && !chart) || showTable" class="table-container">
            <BasicTable
              :tableData="parsedTableData"
              :columns="parsedTableColumns"
            />
          </div>

          <!--显示SQL-->
          <div v-if="showSQL" class="sql-container">
            <highlightjs :autodetect="true" :code="processSQL"></highlightjs>
          </div>

          <!--切换按钮，在一行里面-->
          <div class="toggle">
            <!-- 切换按钮（echarts和table二选一） -->
            <div v-if="chart && table" class="toggle-A">
              <ToggleButton @toggle="toggleView" />
              <span>展示表格</span>
            </div>

            <!-- 切换按钮（是否展示SQL） -->
            <div v-if="sql" class="toggle-B">
              <ToggleButton @toggle="toggleViewSQL" />
              <span>展示代码</span>
            </div>
          </div>
        </div>
      </div>
    </div>

    <!-- 底部评分栏，仅在机器人消息下显示 -->
    <div v-if="!isUser" class="feedback-container">
      <p class="satisfaction-prompt">对该回答满意吗？</p>
      <RatingComponent class="satisfaction-score" />

      <CopyOutlined
        style="
          color: #7f7f7f;
          font-size: 16px;
          margin-left: 10%;
          margin-top: 1px;
        "
      />
      <p class="copy-1">复制</p>
      <ReloadOutlined
        style="
          color: #7f7f7f;
          font-size: 16px;
          margin-left: 2%;
          margin-top: 1px;
        "
      />
      <p class="copy-1">重新生成</p>
    </div>
  </div>
</template>

<script setup>
import { ref, watch, onMounted, computed } from "vue";
import EChartsComponent from "./EChartsComponent.vue";
import RatingComponent from "../components/Score/RatingComponent.vue";
import ToggleButton from "../components/ToggleButton/SwithChartTable.vue";
import { marked } from "marked";
import { CopyOutlined, ReloadOutlined } from "@ant-design/icons-vue";
import "highlight.js/styles/atom-one-light.css"; // 代码高亮样式

import "@kangc/v-md-editor/lib/style/preview.css";
import "@kangc/v-md-editor/lib/theme/style/github.css";
import BasicTable from "../components/Tables/BasicTable.vue"; // 引入 BasicTable 组件

// mode
import "codemirror/mode/markdown/markdown";
import "codemirror/mode/javascript/javascript";
import "codemirror/mode/css/css";
import "codemirror/mode/htmlmixed/htmlmixed";
import "codemirror/mode/vue/vue";
// edit
import "codemirror/addon/edit/closebrackets";
import "codemirror/addon/edit/closetag";
import "codemirror/addon/edit/matchbrackets";
// placeholder
import "codemirror/addon/display/placeholder";
// active-line
import "codemirror/addon/selection/active-line";
// scrollbar
import "codemirror/addon/scroll/simplescrollbars";
import "codemirror/addon/scroll/simplescrollbars.css";
// style
import "codemirror/lib/codemirror.css";

const props = defineProps({
  text: {
    type: String,
    required: true,
    default: "",
  },
  isUser: Boolean,
  sql: {
    type: String,
    default: "",
  },
  chart: {
    type: String,
    default: null,
  },
  table: {
    type: String,
    default: null,
  },
});

// const renderedText = computed(() => marked(props.text));
const renderedText = computed(() => {
  return props.text
    .trim()
    .replace(/\\\[/g, "$$")
    .replace(/\\\]/g, "$$")
    .replace(/\\\(/g, "$")
    .replace(/\\\)/g, "$");
});

const parsedChart = ref(null);
const showTable = ref(false);
const showSQL = ref(false);
const parsedTableData = ref([]);
const parsedTableColumns = ref([]);

// 监视 chart 属性的变化
watch(
  () => props.chart,
  (newValue) => {
    parseChart(newValue);
  },
  { immediate: true }
);

// 监视 table 属性的变化
watch(
  () => props.table,
  (newValue) => {
    parseTable(newValue);
  },
  { immediate: true }
);

onMounted(() => {
  executeScripts();
  parseChart();
  parseTable();
  console.log(
    "调用parseChart和parseTable方法-mounted",
    props.chart,
    props.table
  );
});

// const processSQL = computed(() => marked(props.sql));
const processSQL = computed(() => props.sql.trim());

function toggleView(checked) {
  showTable.value = checked;
}

function toggleViewSQL(checked) {
  showSQL.value = checked;
}

function handleDataSelected(data) {
  // 处理从 EChartsComponent 中选择的数据
  console.log("Selected data:", data);
}

function executeScripts() {
  // 找到所有插入的 script 标签并执行它们
  const scripts = document.querySelectorAll("script");
  scripts.forEach((script) => {
    const newScript = document.createElement("script");
    newScript.textContent = script.textContent;
    document.body.appendChild(newScript);
    document.body.removeChild(newScript);
  });
}

// 解析API传入的Json字符串；（API chart传入的是Json字符串，注意啊）
function parseChart() {
  console.log("开始解析Echarts--1", props.chart);
  if (props.chart) {
    try {
      console.log("开始解析Echarts");
      parsedChart.value = JSON.parse(props.chart);
      console.log("解析完成", parsedChart.value);
    } catch (e) {
      console.error("Failed to parse chart JSON:", e);
      parsedChart.value = null;
    }
  }
}

// 解析API传入的Json字符串（table）
function parseTable() {
  console.log("开始解析Table--1", props.table);
  if (props.table) {
    try {
      console.log("开始解析Table");
      const parsedTable = JSON.parse(props.table);
      parsedTableData.value = parsedTable.data;
      parsedTableColumns.value = parsedTable.columns;
      console.log("解析完成", parsedTableData.value, parsedTableColumns.value);
    } catch (e) {
      console.error("Failed to parse table JSON:", e);
      parsedTableData.value = [];
      parsedTableColumns.value = [];
    }
  }
}
</script>

<style scoped>
:deep(.v-md-editor-preview .github-markdown-body) {
  padding: 0;
}
.v-md-editor-preview {
  padding: 0;
}
.chat-bubble-container {
  display: flex;
  align-items: flex-start;
  margin: 10px;
}

.bot-container {
  display: flex;
  flex-direction: column;
  align-items: flex-start; /* 确保子元素左对齐 */
}

.chart-container {
  width: 100%; /* 宽度调整为100% */
  max-height: 500px; /* 最大高度限制，根据需要调整 */
  overflow: auto; /* 溢出时允许滚动 */
  margin-top: 20px;
  margin-bottom: 20px;
}

.avatar-and-message {
  display: flex;
  align-items: flex-start;

  flex-grow: 1; /* 允许元素增长填满额外空间 */
}

.user-container {
  display: flex;
  justify-content: flex-end;
  align-items: flex-start;
  width: 100%; /* 全宽度 */
}

.chat-bubble {
  padding: 10px 15px;
  border-radius: 10px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
  background-color: #ffffff;
  max-width: 90%; /* 调整最大宽度 */
  word-wrap: break-word;
  overflow: hidden;
}

.user-message {
  background-color: #4b89fe;
  text-align: left;
  color: #ffffff;
  margin-right: 4%;
  margin-bottom: 20px;
  font-size: 18px;
}

.bot-message {
  background-color: #ffffff;
  text-align: left;
  width: 100%;
  min-width: 600px;
  max-width: 80%; /* 调整最大宽度 */
}

.bot-avatar {
  width: 35px;
  height: 35px;
  border-radius: 50%;
  margin-right: 10px;
}

.feedback-container {
  display: flex;
  align-items: center;
  justify-content: flex-start;
  width: 100%;
  margin-top: 5px;
  margin-left: 60px;
}

.satisfaction-prompt {
  margin-bottom: 0px;
  margin-top: 6px;
  color: #7f7f7f;
  margin-right: 20px;
  font-size: 16px;
}

.toggle-A,
.toggle-B {
  display: flex;
  align-items: center; /* 确保按钮和文字垂直居中对齐 */
  margin-top: 10px;
}

.toggle-A span,
.toggle-B span {
  color: #494949;
  margin-left: 20px; /* 增加文字的左边距 */
  min-width: 100px; /* 设置最小宽度 */
}

.toggle {
  display: flex;
  justify-content: start;
}

.copy {
  margin-bottom: 0px;
  margin-top: 6px;
  color: #7f7f7f;
  margin-left: 60px;
  font-size: 15px;
}

.copy-1 {
  margin-bottom: 0px;
  margin-top: 6px;
  color: #7f7f7f;
  margin-left: 6px;
  font-size: 15px;
}

.sql-container {
  margin-top: 3%;
  font-size: 16px;
}
</style>
